from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from book.libs.code import Code
from . import models
import random

# Create your views here.


def login_required(view_func):
    '''登录装饰器'''
    def wrapper(request, *args, **kw_args):
        if request.session.has_key('isLogin'):
            return view_func(request, *args, **kw_args)
        else:
            return redirect('/book/login')
    return wrapper


@login_required
def index(request):
    '''图书列表'''
    # return HttpResponse('books')
    books = models.Book.objects.all()
    return render(request, 'book/books.html', {
        'books': books,
    })


def book(request, id):
    book = models.Book.objects.get(id=id)
    character = book.character_set.all()
    return render(request, 'book/book.html', {
        'book': book,
        'character': character,
    })


def login(request):
    username = ''
    isLogin = False
    if 'username' in request.COOKIES:
        username = request.COOKIES['username']
    if 'isLogin' in request.session:
        isLogin = request.session['isLogin']
    return render(request, 'book/login.html', {
        'username': username,
        'isLogin': isLogin
    })


def check_login(request):
    username = request.POST.get('username')
    password = request.POST.get('password')
    remember = request.POST.get('remember')

    if username == 'honest' and password == '123':
        response = JsonResponse({'res': 1})
        if remember:
            response.set_cookie('username', username, max_age=3600 * 24)
        request.session['isLogin'] = True
        return response
    else:
        return JsonResponse({'res': 0})


def set_cookie(request):
    response = HttpResponse('设置 cookie')
    response.set_cookie('num', 1)
    # cookie 默认浏览器关闭后就过期
    # response.set_cookie('num', 1, max_age=3600*24*14)
    # 使用 datetime 包设置过期的日期
    # response.set_cookie('num', 1, expire=datetime.now() + timedate(days=14))
    return response


def get_cookie(request):
    num = request.COOKIES['num']
    return HttpResponse(num)


def set_session(request):
    request.session['username'] = 'honest'
    request.session['password'] = 123
    # 设置 session 过期时间
    request.session.set_expiry(3600 * 24)
    return HttpResponse('设置session')


def get_session(request):
    username = request.session['username']
    password = request.session['password']
    return HttpResponse(username+str(password))


def clear_session(request):
    # 删除值的部份
    request.session.clear()
    # 删除全部 session
    request.session.flush()


def login_form(request):
    if request.POST:
        username = request.POST.get('username')
        password = request.POST.get('password')
        code = request.POST.get('code')
        if request.session.has_key('code'):
            real_code = request.session['code']
            if username == 'honest' and password == '123' and real_code == code:
                return JsonResponse({
                    'code': 1,
                    'msg': '校验成功'
                })
        return JsonResponse({
            'code': 0,
            'msg': '校验失败'
        })
    else:
        return render(request, 'book/form.html')


def code(request):
    [code, image_stream] = Code(60, 6).generatorImage()
    request.session['code'] = code
    return HttpResponse(image_stream, content_type='image/png')


def generatorRandomString(request):
    code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    randstr = ''
    for i in range(0, 4):
        randstr += code[random.randrange(0, len(code))]
    return randstr
